package com.skydoves.preferenceroomdemo.utils;

import com.skydoves.preferenceroomdemo.ResourceTable;
import com.skydoves.preferenceroomdemo.models.ItemProfile;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

public class ListViewProvider extends BaseItemProvider {
    private final Context context;
    private final List<ItemProfile> profileList;

    public ListViewProvider(Context context) {
        this.context = context;
        this.profileList = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return profileList.size();
    }

    @Override
    public Object getItem(int pos) {
        return profileList.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    public void addItem(ItemProfile itemProfile) {
        this.profileList.add(itemProfile);
        notifyDataChanged();
    }

    @Override
    public Component getComponent(int pos, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_profile, null, false);
        } else {
            cpt = component;
        }
        ItemProfile itemProfile = profileList.get(pos);
        Text title;
        Text content;
        Component cpt1 =
                cpt.findComponentById(ResourceTable.Id_item_profile_title);
        Component cpt2 =
                cpt.findComponentById(ResourceTable.Id_item_profile_content);
        if (cpt1 instanceof Text) {
            title = (Text) cpt1;
            title.setText(itemProfile.getTitle());
        }
        if (cpt2 instanceof Text) {
            content = (Text) cpt2;
            content.setText(itemProfile.getContent());
        }
        return cpt;
    }
}